package com.gzsxy.lesson01.url;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 通过url下载网络资源
 */
public class UrlDown {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://m801.music.126.net/20210821233012/b52342a4e4f882246961edddd532f0ea/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/10413902263/87b8/dd07/6674/9aeca37a3d498dc4252889bedd43c554.m4a");
        //HttpURLConnection通过创建对象获取网络资源  openConnection连接url
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream is = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("3c554.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        is.close();
        urlConnection.disconnect();
    }
}
